package wealk.android.jewels;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.audio.music.Music;
import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.audio.sound.Sound;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;
import org.anddev.andengine.entity.shape.modifier.AlphaModifier;
import org.anddev.andengine.entity.shape.modifier.LoopShapeModifier;
import org.anddev.andengine.entity.shape.modifier.ScaleModifier;
import org.anddev.andengine.entity.shape.modifier.SequenceShapeModifier;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.source.AssetTextureSource;
import org.anddev.andengine.opengl.texture.source.FileTextureSource;
import org.anddev.andengine.opengl.texture.source.ITextureSource;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.HorizontalAlign;
import org.anddev.andengine.util.MathUtils;
import org.anddev.andengine.util.modifier.IModifier;

import com.xkdx.guangguang.util.AESUtil;

import wealk.android.jewels.constants.IConstants;
import wealk.android.jewels.entity.BorderSprite;
import wealk.android.jewels.entity.JewelSprite;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Toast;

/**
 * @author lihl
 */
public class Jewels extends BaseGameActivity implements IOnSceneTouchListener,
		IConstants, IOnAreaTouchListener {

	// ===========================================================
	// Constants
	// ===========================================================

	public static boolean isIntentToPointShop = false;
	int k = 0;
	JewelSprite js6, js7;
	/** 屏幕尺寸 **/
	private static final int CAMERA_WIDTH = 640;// 320;
	private static final int CAMERA_HEIGHT = 960;// 1280;//480;

	/** 场景分层 **/
	public static int SUBMITSCORE = 0;
	public static int SUBMITANDINTENT = 0;
	public static int intentScore = 0;
	public static boolean isLogin = false;

	private static final int LAYER_BACKGROUND = 0;

	private static final int LAYER_JEWELS = LAYER_BACKGROUND + 1;
	private static final int LAYER_BG_CELL = LAYER_JEWELS + 1;
	private static final int LAYER_MASK = LAYER_JEWELS + 1;

	private static final int LAYER_SCORE = LAYER_MASK + 1;

	// ===========================================================
	// Fields
	// ===========================================================

	private Camera mCamera;// 镜头
	protected Scene mMainScene;// 主场景

	/** 游戏模式 **/
	private String mGameModel;

	/** 用户数据 **/
	private String mUserName;
	private String mUserPicFile;
	private int mark1, mark2;
	private int totalscore;

	private String[] markIconPath;

	/** 游戏状态 **/
	private int gametime = 60;
	private boolean mIsMusicOn;
	private boolean mIsSoundOn;
	private boolean mGameRunning;// 游戏的总开关(可处理来电、任务切换等)
	private boolean mIsSwaping;// 交换状态
	private final int MOVE_UP = 1;// 上移
	private final int MOVE_DOWN = 2;// 下移
	private final int MOVE_LEFT = 3;// 左移
	private final int MOVE_RIGHT = 4;// 右移
	private final int FALL = 5;// 下落
	private final int DEAD = 6;// 死局
	private final int RESET = 7;// 待重置
	private final int CHECK = 0;// 执行检测
	private int STATE = CHECK;// 一开始就检测，没有移动命令的时候也一直检测
	private boolean isDown;
	private float scoreratio = 1;
	private Sprite mask;

	/** 游戏音效 **/
	private Sound mSwapErrorSound;// 交换后不消去
	private Sound mFallSound;// 下落
	private Sound mRemoveSound, mRemoveSound1, mRemoveSound2, mRemoveSound3;// 消去
	private Music mStartingSound;// 开场音乐

	private final float SPEED = 17.75f;// 移动速度
	private float moveValue = 0;// 交换移动的临时距离

	/** 背景 **/
	private int mCurBGNum;// 当前使用的背景的编号
	private Texture mBackgroundTexture;
	protected TextureRegion mBackgroundTextureRegion;
	protected TextureRegion mBackground2TextureRegion;// 游戏开始时的一个背景动画

	/** 动画 **/
	protected IModifier scaleLoop;

	// ///////////////////////////////////////////////////////
	Sprite musicoff;
	Sprite musicon;
	Sprite pause;
	Sprite refresh;
	Sprite soundoff;
	Sprite soundon;

	private Texture mMaskTexture;
	private Texture userpic;
	private Texture mMusicOffTexture, mMusicOnTexture, mPauseTexture,
			mRefreshTexture, mSoundOnTexture, mSoundOffTexture;

	protected TextureRegion mMaskTextureRegion;
	protected TextureRegion userpicRegion;

	protected TextureRegion mMusicOffTextureR, mMusicOnTextureR,
			mPauseTextureR, mPauseDownTextureR, mRefreshTextureR,
			mRefreshDownTextureR, mSoundOnTextureR, mSoundOffTextureR;

	/** 钻石 **/
	private HashMap<String, JewelSprite> mHashMap;
	private Texture[] mJewelTexture;
	protected TextureRegion[] mJewelTextureRegion;
	/** 钻石边框 **/
	private BorderSprite mBorder;
	private Texture mBorderTexture;
	private TextureRegion mBorderTextureRegion;
	private TextureRegion mBoardTextureRegion;

	private TextureRegion mBGCellTextureRegion;
	/** bonus **/
	private Sprite mBonus, bonusdot;
	private Texture mBonusBGTexture, mBonusTexture;
	private TextureRegion mBonusBGTextureRegion, mBonusTextureRegion;
	private Texture mBonusDot;
	private TextureRegion mBonusDotR;

	/** LongestChain字体 **/
	private Texture mLongestChainFontTexture;
	private Font mLongestChainFont;
	/** 关卡 **/
	private int mChapter = 1;
	private Texture mChapterTexture;
	private Font mChapterFont;
	private int mLongestChainTemp = 0;
	/** 分数 **/
	private int mScore = 0;
	private String oldScore;
	private Texture mScoreFontTexture;
	private Font mScoreFont;
	private ChangeableText mScoreText, mScoreRatio;
	private int mCurRow, mCurCol;// 当前选中的行、列
	private int mLastRow, mLastCol;// 上一个选中的行、列
	private float mDownX, mDownY, mUpX, mUpY;
	private ArrayList<String> mDeadArrList;// 可消去的钻石地址队列
	private int mTime = 0;// 每一次10秒后还不做任何操作就自动提示

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================
	@Override
	protected void onCreate(Bundle pSavedInstanceState) {
		super.onCreate(pSavedInstanceState);
		StringBuffer sb = new StringBuffer(0);
		while (16 - sb.length() != 0) {
			sb.append("\n");
		}
		oldScore = AESUtil.aesEncrypt(sb.toString());

	}

	@Override
	public Engine onLoadEngine() {
		this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		EngineOptions options = new EngineOptions(false,
				ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(
						CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)
				.setNeedsSound(true);
		options.setNeedsMusic(true);
		return new Engine(options);// 需要播放音效
	}

	@Override
	public void onLoadResources() {
		TextureRegionFactory.setAssetBasePath("gfx/");

		/* Buttons */
		this.mMusicOffTexture = new Texture(1024, 1024,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mMusicOffTextureR = TextureRegionFactory.createFromAsset(
				this.mMusicOffTexture, this, "musicNo.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mMusicOffTexture);

		this.mMusicOnTexture = new Texture(1024, 1024,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mMusicOnTextureR = TextureRegionFactory.createFromAsset(
				this.mMusicOnTexture, this, "music.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mMusicOnTexture);

		this.mPauseTexture = new Texture(1024, 1024,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mPauseTextureR = TextureRegionFactory.createFromAsset(
				this.mPauseTexture, this, "pause.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mPauseTexture);

		this.mRefreshTexture = new Texture(1024, 1024,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mRefreshTextureR = TextureRegionFactory.createFromAsset(
				this.mRefreshTexture, this, "refresh.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mRefreshTexture);

		this.mSoundOnTexture = new Texture(1024, 1024,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mSoundOnTextureR = TextureRegionFactory.createFromAsset(
				this.mSoundOnTexture, this, "sound.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mSoundOnTexture);

		this.mSoundOffTexture = new Texture(1024, 1024,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mSoundOffTextureR = TextureRegionFactory.createFromAsset(
				this.mSoundOffTexture, this, "soundNo.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mSoundOffTexture);

		/* 背景 */
		this.mCurBGNum = MathUtils.random(1, 4);
		String bgPath = "bground" + String.valueOf(1) + ".png";
		this.mBackgroundTexture = new Texture(1024, 2048,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBackgroundTextureRegion = TextureRegionFactory.createFromAsset(
				this.mBackgroundTexture, this, bgPath, 0, 0);

		this.mEngine.getTextureManager().loadTexture(this.mBackgroundTexture);
		/* 钻石 */
		this.mJewelTexture = new Texture[8];
		this.mJewelTextureRegion = new TextureRegion[8];

		for (int i = 0; i < this.mJewelTexture.length; i++) {
			this.mJewelTexture[i] = new Texture(128, 128,
					TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		}
		this.mJewelTextureRegion[0] = TextureRegionFactory.createFromAsset(
				this.mJewelTexture[0], this, "1.png", 0, 0);
		this.mJewelTextureRegion[1] = TextureRegionFactory.createFromAsset(
				this.mJewelTexture[1], this, "2.png", 0, 0);
		this.mJewelTextureRegion[2] = TextureRegionFactory.createFromAsset(
				this.mJewelTexture[2], this, "3.png", 0, 0);
		this.mJewelTextureRegion[3] = TextureRegionFactory.createFromAsset(
				this.mJewelTexture[3], this, "4.png", 0, 0);
		this.mJewelTextureRegion[4] = TextureRegionFactory.createFromAsset(
				this.mJewelTexture[4], this, "5.png", 0, 0);
		this.mJewelTextureRegion[5] = TextureRegionFactory.createFromAsset(
				this.mJewelTexture[5], this, "6.png", 0, 0);
		this.mJewelTextureRegion[6] = TextureRegionFactory.createFromAsset(
				this.mJewelTexture[6], this, "h1.png", 0, 0);
		this.mJewelTextureRegion[7] = TextureRegionFactory.createFromAsset(
				this.mJewelTexture[7], this, "l1.png", 0, 0);
		for (int i = 0; i < this.mJewelTexture.length; i++) {
			this.mEngine.getTextureManager().loadTexture(this.mJewelTexture[i]);
		}
		/* 高分图标，商品图标分数x2 */
		mark1 = 6;
		mark2 = 7;
		/* 钻石边框 */
		this.mBorderTexture = new Texture(64, 64,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBorderTextureRegion = TextureRegionFactory.createFromAsset(
				this.mBorderTexture, this, "selection.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mBorderTexture);
		/* Board */
		// this.mBoardTexture = new Texture(1024, 1024, TextureOptions.DEFAULT);
		// this.mBoardTextureRegion = TextureRegionFactory.createFromAsset
		// (this.mBoardTexture, this, "board.png", 0, 0);
		// this.mEngine.getTextureManager().loadTexture(this.mBoardTexture);
		/* 单元格背景 */
		// this.mBGCellTexture = new Texture(128, 128, TextureOptions.DEFAULT);
		// this.mBGCellTextureRegion = TextureRegionFactory.createFromAsset
		// (this.mBGCellTexture, this, "bg_cell.png", 0, 0);
		// /this.mEngine.getTextureManager().loadTexture(this.mBGCellTexture);
		/* bonus */
		// this.mBonusStaticBGTexture = new Texture(64, 64,
		// TextureOptions.DEFAULT);
		// TextureRegionFactory.createFromAsset
		// (this.mBonusStaticBGTexture, this, "bonus.png", 0, 0);
		// this.mEngine.getTextureManager().loadTexture(this.mBonusStaticBGTexture);

		this.mBonusBGTexture = new Texture(1024, 64,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBonusBGTextureRegion = TextureRegionFactory.createFromAsset(
				this.mBonusBGTexture, this, "bonusbar.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mBonusBGTexture);

		this.mBonusTexture = new Texture(1024, 128,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBonusTextureRegion = TextureRegionFactory.createFromAsset(
				this.mBonusTexture, this, "bonusbar_fill.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mBonusTexture);

		this.mBonusDot = new Texture(64, 64,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBonusDotR = TextureRegionFactory.createFromAsset(this.mBonusDot,
				this, "dot.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mBonusDot);

		/* 蒙版 */
		this.mMaskTexture = new Texture(1024, 1024, TextureOptions.DEFAULT);
		this.mMaskTextureRegion = TextureRegionFactory.createFromAsset(
				this.mMaskTexture, this, "mask.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mMaskTexture);
		/* 字体--longest chain */
		this.mLongestChainFontTexture = new Texture(256, 256,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mLongestChainFont = new Font(this.mLongestChainFontTexture,
				Typeface.create(Typeface.DEFAULT_BOLD, Typeface.BOLD), 26,
				true, 0xff05adee);
		this.mEngine.getTextureManager().loadTexture(
				this.mLongestChainFontTexture);
		this.mEngine.getFontManager().loadFont(this.mLongestChainFont);
		/* 分数板 */
		this.mScoreFontTexture = new Texture(512, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		// this.mScoreFont = FontFactory.createFromAsset(this.mScoreFontTexture,
		// this, "fonts/bluehigh.ttf", 80, true, Color.WHITE);
		this.mScoreFont = new Font(mScoreFontTexture, Typeface.create(
				Typeface.MONOSPACE, Typeface.NORMAL), 26, true, 0xff05adee);
		this.mEngine.getTextureManager().loadTexture(this.mScoreFontTexture);
		this.mEngine.getFontManager().loadFont(this.mScoreFont);

		/* 关卡文字 */
		this.mChapterTexture = new Texture(512, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mChapterFont = FontFactory.createFromAsset(this.mChapterTexture,
				this, "fonts/bluehigh.ttf", 80, true, Color.GREEN);
		this.mEngine.getTextureManager().loadTexture(this.mChapterTexture);
		this.mEngine.getFontManager().loadFont(this.mChapterFont);
		/* 发光精灵 */
		// this.mSparkTexture = new Texture(128, 128, TextureOptions.DEFAULT);
		// this.mSparkTextureRegion = TextureRegionFactory.createFromAsset
		// (this.mSparkTexture, this, "spark1.png", 0, 0);
		// this.mEngine.getTextureManager().loadTexture(this.mSparkTexture);
		// this.mSpark2Texture = new Texture(128, 128, TextureOptions.DEFAULT);
		// this.mSpark2TextureRegion = TextureRegionFactory.createFromAsset
		// (this.mSpark2Texture, this, "spark2.png", 0, 0);
		// this.mEngine.getTextureManager().loadTexture(this.mSpark2Texture);

		this.scaleLoop = new ScaleModifier(0.25f, 1f, 0.5f);
		// new LoopShapeModifier(new SequenceShapeModifier(new
		// ScaleModifier(0.25f, 1f, 0.5f),new ScaleModifier(0.25f, 0.5f, 1f)));

		try {
			this.mSwapErrorSound = SoundFactory
					.createSoundFromAsset(this.mEngine.getSoundManager(), this,
							"raw/A_falsemove.mp3");
			this.mFallSound = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "raw/drop1.ogg");
			this.mRemoveSound = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "raw/A_combo1.mp3");
			this.mRemoveSound1 = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "raw/A_combo2.mp3");
			this.mRemoveSound2 = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "raw/A_combo3.mp3");
			this.mRemoveSound3 = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "raw/A_combo4.mp3");
			this.mStartingSound = MusicFactory.createMusicFromAsset(
					this.mEngine.getMusicManager(), this, "raw/bgm_game.mp3");
			this.mStartingSound.setLooping(true);
			this.mSwapErrorSound.setVolume(50);
			this.mFallSound.setVolume(50);
			this.mRemoveSound.setVolume(50);
			this.mRemoveSound1.setVolume(50);
			this.mRemoveSound2.setVolume(50);
			this.mRemoveSound3.setVolume(50);
			this.mStartingSound.setVolume(50);
		} catch (final IOException e) {
			Debug.e("mGoodMusic Error", e);
		}
	}

	@Override
	public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
			ITouchArea pTouchArea, float pTouchAreaLocalX,
			float pTouchAreaLocalY) {

		if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_DOWN)
			if (pTouchArea.equals(musicoff) || pTouchArea.equals(musicon)) {
				if (this.mIsMusicOn) {
					// Log.d("SSS","Music OFF");
					mIsMusicOn = false;
					mStartingSound.pause();
					musicon.setAlpha(0);
					musicoff.setAlpha(1);
				} else {
					// Log.d("SSS","Music ON");
					mIsMusicOn = true;
					mStartingSound.resume();
					musicon.setAlpha(1);
					musicoff.setAlpha(0);
				}
			} else if (pTouchArea.equals(pause)) {
				// Log.d("SSS","Pause");
				if (this.mGameRunning) {
					// this.STATE=STATE_PAUSE;
					mGameRunning = false;
					// 处理暂停
					Message message1 = new Message();
					message1.what = 1;
					handler.sendMessage(message1);
					if (mIsMusicOn)
						mStartingSound.pause();
				} else {
					mGameRunning = true;
				}
			} else if (pTouchArea.equals(refresh)) {
				if (mGameRunning = true)
					this.STATE = RESET;
			} else if (pTouchArea.equals(soundon)
					|| pTouchArea.equals(soundoff)) {
				// Log.d("SSS","Sound off");
				if (this.mIsSoundOn) {
					mIsSoundOn = false;
					this.mEngine.getSoundManager().setMasterVolume(0);
					soundon.setAlpha(0);
					soundoff.setAlpha(1);
				} else {
					mIsSoundOn = true;
					this.mEngine.getSoundManager().setMasterVolume(1);
					soundon.setAlpha(1);
					soundoff.setAlpha(0);
				}
			}
		return false;
	}

	@Override
	public Scene onLoadScene() {
		this.mMainScene = new Scene(5);
		this.mMainScene.setBackgroundEnabled(true);
		this.mMainScene.setOnSceneTouchListener(this);
		this.mMainScene.setOnAreaTouchListener(this);

		// 初始化
		this.init();

		// 游戏准备
		this.prepareGame();

		// 模式调整
		this.adjustModel();

		// 游戏循环(监听、更新)
		this.gameLoop();

		// 自动智能提示
		this.autoTips();

		return this.mMainScene;
	}

	@Override
	public void onLoadComplete() {
		this.mStartingSound.play();

		// 显示提示框
		// LayoutInflater inflater = getLayoutInflater();
		// View view = inflater.inflate(R.layout.game_alert, (ViewGroup)
		// findViewById(R.id.toast));
		// Toast toast = new Toast(getApplicationContext());
		// toast.setGravity(Gravity.BOTTOM, 0, 0);
		// toast.setDuration(Toast.LENGTH_LONG);
		// toast.setView(view);
		// toast.show();

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (this.mIsMusicOn == true)
			this.mStartingSound.resume();
		Jewels.this.mGameRunning = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		Jewels.this.mGameRunning = false;
		if (this.mIsMusicOn == true)
			mStartingSound.pause();
	}

	// 不同
	@Override
	public boolean onSceneTouchEvent(final Scene pScene,
			final TouchEvent pSceneTouchEvent) {
		// 交换的时候不允许操作
		if (!this.mGameRunning || STATE == MOVE_DOWN || STATE == MOVE_LEFT
				|| STATE == MOVE_RIGHT || STATE == MOVE_UP || STATE == FALL) {
			return false;
		} else if (pSceneTouchEvent.getX() - PX < 0 // 是否点击有效区域
				|| pSceneTouchEvent.getX() - PX > (CELL_WIDTH + 1) * 8
				|| pSceneTouchEvent.getY() - PY < 0
				|| pSceneTouchEvent.getY() - PY > (CELL_HEIGHT + 1) * 8) {
			return false;
		} else {
			if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_DOWN) {
				System.out.println("MotionEvent.ACTION_DOWN");
				isDown = true;
				this.mDownX = pSceneTouchEvent.getX();
				this.mDownY = pSceneTouchEvent.getY();
			} else if (isDown) {
				this.mUpX = pSceneTouchEvent.getX();
				this.mUpY = pSceneTouchEvent.getY();
				mLongestChainTemp = 0;// 清空临时记录的最长连接
				scoreratio = (float) (mChapter * 0.2 + 0.8);// update scoreratio
				this.mScoreRatio.setText(String.format("%.1f倍", scoreratio));
				// 判断滑动
				if (mUpX - mDownX > CELL_WIDTH + 1
						|| mDownX - mUpX > CELL_WIDTH + 1
						|| mUpY - mDownY > CELL_HEIGHT + 1
						|| mDownY - mUpY > CELL_HEIGHT + 1) {
					this.mBorder.getSprite().setVisible(false);

					this.mLastRow = (int) ((this.mDownX - PX) / (CELL_WIDTH + 1));
					this.mLastCol = (int) ((this.mDownY - PY) / (CELL_HEIGHT + 1));

					float h2, h = mUpX - mDownX;
					float v2, v = mUpY - mDownY;
					h2 = h < 0 ? -h : h;
					v2 = v < 0 ? -v : v;

					if (h2 > v2) {
						this.mCurCol = this.mLastCol;// 横向滑动
						if (h > 0) {
							this.mCurRow = this.mLastRow + 1;// 右滑
							this.STATE = this.MOVE_RIGHT;
							// Log.e("SSS","RowCur"+String.valueOf(mCurRow));
							// Log.e("SSS","ColCur"+String.valueOf(mCurCol));
						} else {
							this.mCurRow = this.mLastRow - 1;// 左滑
							this.STATE = this.MOVE_LEFT;

						}
					} else {
						this.mCurRow = this.mLastRow;// 纵向滑动
						if (v > 0) {
							this.mCurCol = this.mLastCol + 1;// 下滑
							this.STATE = this.MOVE_DOWN;
						} else {
							this.mCurCol = this.mLastCol - 1;// 上滑
							this.STATE = this.MOVE_UP;
						}
					}
					isDown = false;
				} else if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_UP) {
					// 非滑动，即点击
					this.mLastRow = (int) ((this.mBorder.getSprite().getX() - PX) / (CELL_WIDTH + 1));
					this.mLastCol = (int) ((this.mBorder.getSprite().getY() - PY) / (CELL_HEIGHT + 1));
					this.mCurRow = (int) ((this.mDownX - PX) / (CELL_WIDTH + 1));
					this.mCurCol = (int) ((this.mDownY - PY) / (CELL_HEIGHT + 1));

					if (this.isNext()) {// 相邻
						this.mBorder.setMapPosition(-2, -2);
						this.mBorder.getSprite().setVisible(false);
						this.setMoveDirection();
					} else if (this.mCurRow == this.mLastRow
							&& this.mCurCol == this.mLastCol) {// 两次点击是同一个
						this.mLastRow = -2;
						this.mLastCol = -2;
						this.mBorder.setMapPosition(-2, -2);
						this.mBorder.getSprite().setVisible(false);
					} else {// 不相邻不是同一个
						this.mBorder.setMapPosition(this.mCurRow, this.mCurCol);
						this.mBorder.getSprite().setVisible(true);
					}
					isDown = false;
				}
			}
			return true;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			mGameRunning = false;
			if (mIsMusicOn)
				mStartingSound.pause();
			Jewels.this.onGamePause();
			return true;
		} else {
			return false;
		}
	}

	// ===========================================================
	// Methods
	// ===========================================================

	/**
	 * 游戏初始化
	 */
	private void init() {
		this.initMode();
		this.initFields();
		this.initBG();
		this.initUserinfo();
		// this.initCellBG();
		this.initJewels();
		this.initBorderSprite();

		this.initMask();

		this.initBonus();
		// this.initLongestChain();
		this.initScore();
		this.initSound();
	}

	/**
	 * 初始化用户名称、头像、积分
	 */
	private void initUserinfo() {
		Intent intent = getIntent();
		// 头像图片
		this.mUserPicFile = intent.getStringExtra("userPicFile");
		File upc = null;
		ITextureSource exa;
		if (mUserPicFile != null) {
			upc = new File(this.mUserPicFile);
			if (upc.exists()) {
				exa = new FileTextureSource(upc);
			} else {
				exa = new AssetTextureSource(this, "gfx/userpic.png");
			}
		} else {
			exa = new AssetTextureSource(this, "gfx/userpic.png");
		}
		this.userpic = new Texture(1024, 1024,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.userpicRegion = TextureRegionFactory.createFromSource(userpic,
				exa, 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.userpic);
		final Sprite userpic = new Sprite(50, 38, 102, 102, userpicRegion);
		userpic.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

		// 用户名
		this.mUserName = intent.getStringExtra("userName");
		if (mUserName == null)
			mUserName = "枫叶";
		final Text UN = new Text(52, 140, this.mLongestChainFont,
				this.mUserName, HorizontalAlign.CENTER);
		UN.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		UN.setAlpha(1);
		UN.setScale(0.8f, 0.8f);

		// 商标
		markIconPath = intent.getStringArrayExtra("markIconPath");
		if (markIconPath != null && markIconPath[0] != null
				&& markIconPath[1] != null) {
			this.mJewelTextureRegion[6] = TextureRegionFactory.createFromAsset(
					this.mJewelTexture[6], this, markIconPath[0], 0, 0);
			this.mJewelTextureRegion[7] = TextureRegionFactory.createFromAsset(
					this.mJewelTexture[7], this, markIconPath[1], 0, 0);
			this.mEngine.getTextureManager().loadTexture(this.mJewelTexture[6]);
			this.mEngine.getTextureManager().loadTexture(this.mJewelTexture[7]);
		}

		// 总分数
		this.totalscore = intent.getIntExtra("totalscore", 0);
		final Text TTS = new Text(388, 42, this.mScoreFont, String.format(
				"%07d", totalscore), HorizontalAlign.LEFT);
		TTS.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		TTS.setAlpha(1);
		TTS.setScale(2.75f, 1.9f);

		this.mMainScene.getLayer(LAYER_MASK).addEntity(TTS);
		this.mMainScene.getLayer(LAYER_MASK).addEntity(userpic);
		this.mMainScene.getLayer(LAYER_MASK).addEntity(UN);
	}

	/**
	 * 初始化蒙版（遮挡board露出的部分）及声音按钮
	 */
	private void initMask() {
		// UI蒙版

		mask = new Sprite(PX, PY, 71 * 8, 71 * 8, mMaskTextureRegion);
		mask.setVisible(false);
		musicoff = new Sprite(399, 109, 100, 80, mMusicOffTextureR);
		musicon = new Sprite(399, 109, 100, 80, mMusicOnTextureR);
		pause = new Sprite(187, 109, 112, 80, mPauseTextureR);
		refresh = new Sprite(299, 109, 100, 80, mRefreshTextureR);
		soundoff = new Sprite(499, 109, 110, 80, mSoundOffTextureR);
		soundon = new Sprite(499, 109, 110, 80, mSoundOnTextureR);

		musicoff.setAlpha(0);
		soundoff.setAlpha(0);

		this.mMainScene.registerTouchArea(this.musicoff);
		// this.mMainScene.registerTouchArea(this.musicon);
		this.mMainScene.registerTouchArea(this.pause);
		this.mMainScene.registerTouchArea(this.refresh);
		this.mMainScene.registerTouchArea(this.soundoff);
		// this.mMainScene.registerTouchArea(this.soundon);

		mask.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		musicoff.setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);
		musicon.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		pause.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		refresh.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		soundoff.setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);
		soundon.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

		this.mMainScene.getLayer(LAYER_MASK).addEntity(mask);
		this.mMainScene.getLayer(LAYER_MASK).addEntity(musicon);
		this.mMainScene.getLayer(LAYER_MASK).addEntity(pause);
		this.mMainScene.getLayer(LAYER_MASK).addEntity(soundon);
		this.mMainScene.getLayer(LAYER_MASK).addEntity(musicoff);
		this.mMainScene.getLayer(LAYER_MASK).addEntity(soundoff);
		this.mMainScene.getLayer(LAYER_MASK).addEntity(refresh);
	}

	/**
	 * 初始化游戏模式
	 */
	private void initMode() {
		this.mGameModel = "timed";
	}

	/**
	 * 游戏模式调整
	 */
	private void adjustModel() {
		// 时间模式得加一个定时器
		if (this.mGameModel.equals("timed")) {
			// this.mBonus.setWidth(480);
			mBonus.getTextureRegion().setTexturePosition(0, 0);
			this.bonusdot.setPosition(107 + 480, 203);
			this.mMainScene.registerUpdateHandler(new TimerHandler(1f, true,
					new ITimerCallback() {
						@Override
						public void onTimePassed(TimerHandler pTimerHandler) {
							if (mGameRunning) {
								gametime -= 0.8 + 0.2 * mChapter;
								// mBonus.setWidth((float) (480)/60*gametime);
								mBonus.getTextureRegion().setTexturePosition(
										-480 / 60 * (60 - gametime), 0);
								mBonus.setPosition(
										125 - 480 / 60 * (60 - gametime), 210);
								bonusdot.setPosition(
										107 + (480) / 60 * gametime, 203);
								if (gametime <= 0) {
									// Message message1 = new Message();
									// message1.what = 4;
									// handler.sendMessage(message1);
									mGameRunning = false;
									Message message = new Message();
									message.what = 0;
									handler.sendMessage(message);
								}
							}
						}
					}));
		}
	}

	/**
	 * 线程之外发送消息的句柄
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				onGameOver();
				// toMenuView();
				break;
			case 1:
				onGamePause();
				break;
			case 2:
				showLongMessage("死局");
				break;
			case 3:
				doTips();
				break;
			case 4:
				showLongMessage("时间到");
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 游戏准备时间
	 */
	private void prepareGame() {
		this.mMainScene.registerUpdateHandler(new TimerHandler(1.0f,
				new ITimerCallback() {
					@Override
					public void onTimePassed(final TimerHandler pTimerHandler) {
						mMainScene.unregisterUpdateHandler(pTimerHandler);
						gametime = 60;
						Jewels.this.mGameRunning = true;
					}
				}));
	}

	/**
	 * 初始化音效
	 */
	private void initSound() {
		this.mIsMusicOn = true;
		this.mIsSoundOn = true;

	}

	private boolean checkPoint() {
		
		StringBuffer sb = new StringBuffer(mScore);
		while (16 - sb.length() != 0) {
			sb.append("\n");
		}
		
		if (AESUtil.aesEncrypt(sb.toString()).equals(oldScore)) {
			return true;
		}
		return false;
	}

	/**
	 * 游戏循环（不同）
	 */
	private void gameLoop() {
		this.mMainScene.registerUpdateHandler(new IUpdateHandler() {

			@Override
			public void reset() {
			}

			@Override
			public void onUpdate(float pSecondsElapsed) {

				if (Jewels.this.mGameRunning) {
					switch (STATE) {
					case MOVE_UP:
						moveUp();
						break;
					case MOVE_DOWN:
						moveDown();
						break;
					case MOVE_LEFT:
						moveLeft();
						break;
					case MOVE_RIGHT:
						moveRight();
						break;
					case CHECK:
						// removeHorizontal(); //水平消去
						// removeVrtical(); //垂直消去
						if (removeHorizontal() == 1 || removeVrtical() == 1)
							addBonus();
						changeState();// checkMapDead(); //死局检测
						break;
					case FALL:
						refreshScale(); // 消去动画
						fillEmpty(); // 填充空缺
						// 添加的
						initBorderSprite();
						break;
					// 添加
					case RESET:
						mGameRunning = false;
						mDeadArrList.clear();
						gametime = 60;
						mScore = 0;
						mScoreText.setText("0000000");
						mChapter = 1;
						mBorder.setMapPosition(-2, -2);
						initFields();
						moveValue = 0;
						reSetJewels();
						break;
					case DEAD:
						reSetJewels();
						break;
					default:
						break;
					}
				}
			}
		});
	}

	private void reSetJewels() {
		this.mGameRunning = false;
		this.mMainScene.getLayer(LAYER_JEWELS).sortEntities();
		for (int i = this.mMainScene.getLayer(LAYER_JEWELS).getEntityCount() - 1; i >= 0; --i)
			this.mMainScene.getLayer(LAYER_JEWELS).removeEntity(i);
		this.initJewels();
		STATE = CHECK;
		this.mGameRunning = true;
	}

	/**
	 * 钻石自动发光提示(可消去的)
	 */
	private void autoTips() {
		this.mMainScene.registerUpdateHandler(new TimerHandler(0.5f, true,
				new ITimerCallback() {
					@Override
					public void onTimePassed(TimerHandler pTimerHandler) {
						if (mGameRunning) {
							if (STATE == CHECK) {
								mTime++;
								if (mTime >= 8) {
									// 提示
									Message msg = new Message();
									msg.what = 3;
									handler.sendMessage(msg);
									mTime = 0;
								}
							} else {
								mTime = 0;
							}
						}
					}
				}));
	}

	/**
	 * 初始化字段
	 */
	private void initFields() {
		this.mLastRow = -2;
		this.mLastCol = -2;
		this.mIsSwaping = false;
		mDeadArrList = new ArrayList<String>();
	}

	/**
	 * 初始化背景
	 */
	private void initBG() {
		final Sprite background = new Sprite(0, 0,
				this.mBackgroundTextureRegion);
		this.mMainScene.getLayer(LAYER_BACKGROUND).addEntity(background);
	}

	/**
	 * 初始化关卡进度条
	 */
	private void initBonus() {

		// 时间背景
		final Sprite bonus = new Sprite(122, 210, 480, 22,
				this.mBonusBGTextureRegion);
		this.mMainScene.getLayer(LAYER_MASK).addEntity(bonus);
		this.mBonus = new Sprite(125, 210, 480, 22, this.mBonusTextureRegion);
		this.bonusdot = new Sprite(107, 203, 54, 54, this.mBonusDotR);
		// this.mBonus.setWidth(0);
		this.mMainScene.getLayer(LAYER_SCORE).addEntity(this.mBonus);
		this.mMainScene.getLayer(LAYER_SCORE).addEntity(this.bonusdot);
	}

	/**
	 * 初始化分数面板
	 */
	private void initScore() {

		this.mScoreText = new ChangeableText(460, 887, this.mScoreFont,
				"0000000", 7);
		this.mScoreText.setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mScoreText.setAlpha(1);
		this.mScoreText.setScale(1f, 1.2f);
		this.mMainScene.getLayer(LAYER_SCORE).addEntity(this.mScoreText);

		this.mScoreRatio = new ChangeableText(175, 887, this.mScoreFont,
				"1.0倍", 5);
		this.mScoreRatio.setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mScoreRatio.setAlpha(1);
		this.mScoreRatio.setScale(1.2f, 1.2f);
		this.mMainScene.getLayer(LAYER_SCORE).addEntity(this.mScoreRatio);
	}

	/**
	 * 初始化钻石
	 */
	private void initJewels() {
		this.mHashMap = new HashMap<String, JewelSprite>();
		for (int i = 0; i < CELLS_HORIZONTAL; i++) {
			for (int j = 0; j < CELLS_VERTICAL; j++) {
				String key = getKey(i, j);
				JewelSprite value = getRandomJewel(i, j);
				while ((checkHorizontal(value).size() >= 3 || checkVertical(
						value).size() >= 3)) {
					value = getRandomJewel(i, j);
				}
				mHashMap.put(key, value);
				this.mMainScene.getLayer(LAYER_JEWELS).addEntity(
						this.mHashMap.get(key).getJewel());
			}
		}
		k = 0;
	}

	/**
	 * 初始化钻石边框精灵
	 */
	private void initBorderSprite() {
		this.mBorder = new BorderSprite(-2, -2, mBorderTextureRegion);
		this.mBorder.setMapPosition(-2, -2);
		this.mBorder.getSprite().setVisible(false);
		this.mBorder.getSprite().setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mBorder.getSprite().addShapeModifier(
				new LoopShapeModifier(new SequenceShapeModifier(
						new AlphaModifier(0.4f, 1, 0), new AlphaModifier(0.2f,
								0, 1))));
		this.mMainScene.getLayer(LAYER_BG_CELL).addEntity(
				this.mBorder.getSprite());
	}

	/**
	 * 执行发光提示
	 */
	private void doTips() {
		// Log.d("tag", "发光提示1");
		/*
		 * if(mSpark == null){ Log.d("tag", "发光提示2"); mSpark = new Sprite(0, 0,
		 * mSparkTextureRegion); mSpark2 = new Sprite(0, 0,
		 * mSpark2TextureRegion); mSpark.setVisible(false);
		 * mSpark2.setVisible(false);
		 * this.mMainScene.getTopLayer().addEntity(mSpark);
		 * this.mMainScene.getTopLayer().addEntity(mSpark2); }
		 */
		if (mDeadArrList.size() > 0) {
			// Log.d("tag", "发光提示3");
			/*
			 * String key = mDeadArrList.get(MathUtils.random(0,
			 * mDeadArrList.size()-1));
			 * mSpark.setPosition(Integer.parseInt(key.substring(0,
			 * 1))*(CELL_WIDTH+1) +PX + 8, Integer.parseInt(key.substring(1,
			 * 2))*(CELL_HEIGHT+1) +PY+ 8);
			 * mSpark2.setPosition(Integer.parseInt(key.substring(0,
			 * 1))*(CELL_WIDTH+1) +PX + 4, Integer.parseInt(key.substring(1,
			 * 2))*(CELL_HEIGHT+1) +PY+ 4); mSpark.setVisible(true);
			 * mSpark2.setVisible(true); mSpark2.addShapeModifier(new
			 * RotationModifier(1.5f, 0, 90)); mSpark.addShapeModifier(new
			 * SequenceShapeModifier( new ScaleModifier(1.5f, 0.4f, 0.6f),new
			 * ScaleModifier(0.1f, 0.6f, 0f))); mSpark2.addShapeModifier(new
			 * SequenceShapeModifier( new ScaleModifier(1.5f, 0.5f, 1.1f),new
			 * ScaleModifier(0.1f, 1.1f, 0f)));
			 */

			mHashMap.get(
					mDeadArrList.get(MathUtils.random(0,
							mDeadArrList.size() - 1)))
					.getJewel()
					.addShapeModifier(
							new SequenceShapeModifier(new AlphaModifier(0.5f,
									1f, 0.1f),
									new AlphaModifier(0.5f, 0.1f, 1f)));
		}
	}

	/**
	 * 设置交换移动方向
	 */
	private void setMoveDirection() {
		if (this.mLastRow == this.mCurRow && this.mLastCol > this.mCurCol) {
			this.STATE = this.MOVE_UP;
		}
		if (this.mLastRow == this.mCurRow && this.mLastCol < this.mCurCol) {
			this.STATE = this.MOVE_DOWN;
		}
		if (this.mLastRow > this.mCurRow && this.mLastCol == this.mCurCol) {
			this.STATE = this.MOVE_LEFT;
		}
		if (this.mLastRow < this.mCurRow && this.mLastCol == this.mCurCol) {
			this.STATE = this.MOVE_RIGHT;
		}
	}

	/**
	 * 更新缩放动画
	 */
	private void refreshScale() {
		for (int i = 0; i < CELLS_HORIZONTAL; i++) {
			for (int j = 0; j < CELLS_VERTICAL; j++) {
				if (mHashMap.get(getKey(j, i)) != null
						&& mHashMap.get(getKey(j, i)).getState() == STATE_SCALEINT) {
					mHashMap.get(getKey(j, i)).doScale();
				}
			}
		}
	}

	/**
	 * 向上交换移动
	 */
	private void moveUp() {
		if (mIsSwaping) {
			if (moveValue < CELL_HEIGHT + 1) {
				moveValue += SPEED;
				final float x = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getX();
				final float curY = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getY();
				final float lastY = this.mHashMap
						.get(getKey(mLastRow, mLastCol)).getJewel().getY();
				mHashMap.get(getKey(mCurRow, mCurCol)).getJewel()
						.setPosition(x, curY + SPEED);
				mHashMap.get(getKey(mLastRow, mLastCol)).getJewel()
						.setPosition(x, lastY - SPEED);
			} else {
				swapInHashMap();
				STATE = CHECK;
				moveValue = 0;
				mIsSwaping = false;
				this.mLastRow = -2;
				this.mLastCol = -2;
			}
		} else {
			if (moveValue < CELL_HEIGHT + 1) {
				moveValue += SPEED;
				final float x = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getX();
				final float curY = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getY();
				final float lastY = this.mHashMap
						.get(getKey(mLastRow, mLastCol)).getJewel().getY();
				mHashMap.get(getKey(mCurRow, mCurCol)).getJewel()
						.setPosition(x, curY + SPEED);
				mHashMap.get(getKey(mLastRow, mLastCol)).getJewel()
						.setPosition(x, lastY - SPEED);
			} else {
				swapInHashMap();
				if (isSwapFall()) {
					this.mFallSound.play();
					STATE = CHECK;
					this.mLastRow = -2;
					this.mLastCol = -2;
				} else {
					this.mSwapErrorSound.play();
					mIsSwaping = true;

					// this.mBorder.getSprite().setVisible(true);
				}
				moveValue = 0;
			}
		}
	}

	/**
	 * 向下交换移动
	 */
	private void moveDown() {
		if (mIsSwaping) {
			if (moveValue < CELL_HEIGHT + 1) {
				moveValue += SPEED;
				final float x = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getX();
				final float curY = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getY();
				final float lastY = this.mHashMap
						.get(getKey(mLastRow, mLastCol)).getJewel().getY();
				mHashMap.get(getKey(mCurRow, mCurCol)).getJewel()
						.setPosition(x, curY - SPEED);
				mHashMap.get(getKey(mLastRow, mLastCol)).getJewel()
						.setPosition(x, lastY + SPEED);
			} else {
				swapInHashMap();
				STATE = CHECK;
				moveValue = 0;
				mIsSwaping = false;
				this.mLastRow = -2;
				this.mLastCol = -2;
			}
		} else {
			if (moveValue < CELL_HEIGHT + 1) {
				moveValue += SPEED;
				final float x = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getX();
				final float curY = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getY();
				final float lastY = this.mHashMap
						.get(getKey(mLastRow, mLastCol)).getJewel().getY();
				mHashMap.get(getKey(mCurRow, mCurCol)).getJewel()
						.setPosition(x, curY - SPEED);
				mHashMap.get(getKey(mLastRow, mLastCol)).getJewel()
						.setPosition(x, lastY + SPEED);
			} else {
				swapInHashMap();
				if (isSwapFall()) {
					this.mFallSound.play();
					STATE = CHECK;
					this.mLastRow = -2;
					this.mLastCol = -2;
				} else {
					this.mSwapErrorSound.play();
					mIsSwaping = true;
					// this.mBorder.getSprite().setVisible(true);
				}
				moveValue = 0;
			}
		}
	}

	/**
	 * 向左交换移动
	 */
	private void moveLeft() {
		if (mIsSwaping) {
			if (moveValue < CELL_HEIGHT + 1) {
				moveValue += SPEED;
				final float curX = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getX();
				final float lastX = this.mHashMap
						.get(getKey(mLastRow, mLastCol)).getJewel().getX();
				final float y = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getY();
				mHashMap.get(getKey(mCurRow, mCurCol)).getJewel()
						.setPosition(curX + SPEED, y);
				mHashMap.get(getKey(mLastRow, mLastCol)).getJewel()
						.setPosition(lastX - SPEED, y);
			} else {
				swapInHashMap();
				STATE = CHECK;
				moveValue = 0;
				mIsSwaping = false;
				this.mLastRow = -2;
				this.mLastCol = -2;
			}
		} else {
			if (moveValue < CELL_HEIGHT + 1) {
				moveValue += SPEED;
				final float curX = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getX();
				final float lastX = this.mHashMap
						.get(getKey(mLastRow, mLastCol)).getJewel().getX();
				final float y = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getY();
				mHashMap.get(getKey(mCurRow, mCurCol)).getJewel()
						.setPosition(curX + SPEED, y);
				mHashMap.get(getKey(mLastRow, mLastCol)).getJewel()
						.setPosition(lastX - SPEED, y);
			} else {
				swapInHashMap();
				if (isSwapFall()) {
					this.mFallSound.play();
					STATE = CHECK;
					this.mLastRow = -2;
					this.mLastCol = -2;
				} else {
					this.mSwapErrorSound.play();
					mIsSwaping = true;
					// this.mBorder.getSprite().setVisible(true);
				}
				moveValue = 0;
			}
		}
	}

	/**
	 * 向右交换移动
	 */
	private void moveRight() {
		if (mIsSwaping) {
			if (moveValue < CELL_HEIGHT + 1) {
				moveValue += SPEED;
				final float curX = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getX();
				final float lastX = this.mHashMap
						.get(getKey(mLastRow, mLastCol)).getJewel().getX();
				final float y = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getY();
				mHashMap.get(getKey(mCurRow, mCurCol)).getJewel()
						.setPosition(curX - SPEED, y);
				mHashMap.get(getKey(mLastRow, mLastCol)).getJewel()
						.setPosition(lastX + SPEED, y);
			} else {
				swapInHashMap();
				STATE = CHECK;
				moveValue = 0;
				mIsSwaping = false;
				this.mLastRow = -2;
				this.mLastCol = -2;
			}
		} else {
			if (moveValue < CELL_HEIGHT + 1) {
				moveValue += SPEED;
				final float curX = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getX();
				final float lastX = this.mHashMap
						.get(getKey(mLastRow, mLastCol)).getJewel().getX();
				final float y = this.mHashMap.get(getKey(mCurRow, mCurCol))
						.getJewel().getY();
				mHashMap.get(getKey(mCurRow, mCurCol)).getJewel()
						.setPosition(curX - SPEED, y);
				mHashMap.get(getKey(mLastRow, mLastCol)).getJewel()
						.setPosition(lastX + SPEED, y);
			} else {
				swapInHashMap();
				if (isSwapFall()) {
					this.mFallSound.play();
					STATE = CHECK;// ////////////////////
					this.mLastRow = -2;
					this.mLastCol = -2;
				} else {
					this.mSwapErrorSound.play();
					mIsSwaping = true;
					// this.mBorder.getSprite().setVisible(true);
				}
				moveValue = 0;
			}
		}
	}

	/**
	 * 填充空缺位置
	 */
	private void fillEmpty() {
		// 所有消去状态的钻石冒泡到顶部
		for (int i = 0; i < CELLS_HORIZONTAL; i++) {
			for (int j = 0; j < CELLS_VERTICAL; j++) {
				if (mHashMap.get(getKey(j, i)).getState() == STATE_DEAD) {
					int p = i;
					while ((p - 1) >= 0
							&& mHashMap.get(getKey(j, p - 1)).getState() != STATE_DEAD) {
						JewelSprite temp = mHashMap.get(getKey(j, p - 1));
						mHashMap.put(getKey(j, p - 1),
								mHashMap.get(getKey(j, p)));
						mHashMap.put(getKey(j, p), temp);
						p--;
					}
				}
			}
		}
		// 在HashMap里补充消去的钻石

		int i = 0;
		for (int j = 0; j < CELLS_VERTICAL; j++) {
			if (mHashMap.get(getKey(j, i)).getState() == STATE_DEAD) {
				int v = 0;
				for (v = 0; j + v < CELLS_VERTICAL
				// && mHashMap.get(getKey(j, i)).getStyle() ==
				// mHashMap.get(getKey(j, i+v)).getStyle()
						&& STATE_DEAD == mHashMap.get(getKey(j, i + v))
								.getState(); v++) {
					final Sprite temp = mHashMap.get(getKey(j, i + v))
							.getJewel();
					runOnUpdateThread(new Runnable() {
						@Override
						public void run() {
							/* Now it is save to remove the entity! */
							mEngine.getScene().getTopLayer().removeEntity(temp);
							BufferObjectManager.getActiveInstance()
									.unloadBufferObject(temp.getVertexBuffer());
						}
					});
					// Log.d("entity",String.valueOf(mMainScene.getLayer(LAYER_JEWELS).getEntityCount()));
				}
				for (int z = v; z > 0; z--) {
					JewelSprite newJewel = getRandomJewel(j, -z);
					mMainScene.getLayer(LAYER_JEWELS).addEntity(
							newJewel.getJewel());
					mHashMap.put(getKey(j, v - z), newJewel);
				}
			}
		}

		// 在场景里下落
		int count = 0;
		for (i = 0; i < CELLS_HORIZONTAL; i++) {
			for (int j = CELLS_VERTICAL - 1; j >= 0; j--) {
				if (mHashMap.get(getKey(i, j)).getJewel().getY() < j
						* (CELL_HEIGHT + 1.0) + PY - 1)// 还没有下落到位
				{
					mHashMap.get(getKey(i, j))
							.getJewel()
							.setPosition(
									PX + i * (CELL_WIDTH + 1),
									(float) (mHashMap.get(getKey(i, j))
											.getJewel().getY() + (CELL_HEIGHT + 1.0) / 2));
					count++;
				}
				if (mHashMap.get(getKey(i, j)).getState() == STATE_SCALEINT) {
					count++;
				}
			}
		}
		if (count == 0 && STATE == FALL) {
			// Log.d("SSS","ChangeState Fall");
			mDeadArrList.clear();// 试探后可以消去的队列
			STATE = CHECK;
		}
	}

	/**
	 * 死局检测
	 */
	private void checkMapDead() {
		int count = 0;
		for (int i = 0; i < CELLS_HORIZONTAL; i++) {
			for (int j = 0; j < CELLS_VERTICAL; j++) {
				if (mHashMap.get(getKey(j, i)).getState() == STATE_NORMAL) {
					count++;
				}
			}
		}
		if (count == 64) {
			// 所有遍历一遍
			this.mDeadArrList.clear();// /////////////////////////////////////
			// if(this.mDeadArrList.size() == 0){
			int i = 0;
			while (i < CELLS_HORIZONTAL) {
				int j = 0;
				while (j < CELLS_HORIZONTAL) {
					if (checkDead(mHashMap.get(getKey(j, i))) == true) {
						this.mDeadArrList.add(getKey(j, i));
					}
					j += 1;
				}
				i += 1;
			}
			if (this.mDeadArrList.size() == 0) {
				STATE = DEAD;
			}
			// }
		}
	}

	// 不同
	/**
	 * 单个钻石的交换试探检测
	 */
	private boolean checkDead(final JewelSprite sprite) {
		/*
		 * boolean flag = false; int row = sprite.getRow(); int col =
		 * sprite.getCol(); JewelSprite temp = sprite; //向上试探 if((col - 1) >=
		 * 0){ mHashMap.put(getKey(row, col), mHashMap.get(getKey(row, col-1)));
		 * mHashMap.put(getKey(row, col-1), temp); int v = 0; for(v = 1; col-1-v
		 * >= 0 && mHashMap.get(getKey(row,col-1)).getStyle() ==
		 * mHashMap.get(getKey(row, col-1-v)).getStyle() &&
		 * mHashMap.get(getKey(row, col-1)).getState() ==
		 * mHashMap.get(getKey(row, col-1-v)).getState(); v++); if(v >= 3){ flag
		 * = true; } mHashMap.put(getKey(row, col-1), mHashMap.get(getKey(row,
		 * col))); mHashMap.put(getKey(row, col), temp); } //向下试探 if((col + 1) <
		 * CELLS_HORIZONTAL){ mHashMap.put(getKey(row, col),
		 * mHashMap.get(getKey(row, col+1))); mHashMap.put(getKey(row, col+1),
		 * temp); int v1 = 0; for(v1 = 1; col+1+v1 < CELLS_HORIZONTAL &&
		 * mHashMap.get(getKey(row,col+1)).getStyle() ==
		 * mHashMap.get(getKey(row, col+1+v1)).getStyle() &&
		 * mHashMap.get(getKey(row, col+1)).getState() ==
		 * mHashMap.get(getKey(row, col+1+v1)).getState(); v1++); if(v1 >= 3){
		 * flag = true; } mHashMap.put(getKey(row, col+1),
		 * mHashMap.get(getKey(row, col))); mHashMap.put(getKey(row, col),
		 * temp); } //向左试探 if((row - 1) >= 0){ mHashMap.put(getKey(row, col),
		 * mHashMap.get(getKey(row-1, col))); mHashMap.put(getKey(row-1, col),
		 * temp); int v2 = 0; for(v2 = 1; row-1-v2 >= 0 &&
		 * mHashMap.get(getKey(row-1,col)).getStyle() ==
		 * mHashMap.get(getKey(row-1-v2, col)).getStyle() &&
		 * mHashMap.get(getKey(row-1, col)).getState() ==
		 * mHashMap.get(getKey(row-1-v2, col)).getState(); v2++); if(v2 >= 3){
		 * flag = true; } mHashMap.put(getKey(row-1, col),
		 * mHashMap.get(getKey(row, col))); mHashMap.put(getKey(row, col),
		 * temp); } //向右试探 if((row + 1) < CELLS_VERTICAL){
		 * mHashMap.put(getKey(row, col), mHashMap.get(getKey(row+1, col)));
		 * mHashMap.put(getKey(row+1, col), temp); int v3 = 0; for(v3 = 1;
		 * row+1+v3 < CELLS_VERTICAL &&
		 * mHashMap.get(getKey(row+1,col)).getStyle() ==
		 * mHashMap.get(getKey(row+1+v3, col)).getStyle() &&
		 * mHashMap.get(getKey(row+1, col)).getState() ==
		 * mHashMap.get(getKey(row+1+v3, col)).getState(); v3++); if(v3 >= 3){
		 * flag = true; } mHashMap.put(getKey(row+1, col),
		 * mHashMap.get(getKey(row, col))); mHashMap.put(getKey(row, col),
		 * temp); } return flag;
		 */
		int row = sprite.getRow();
		int col = sprite.getCol();
		JewelSprite temp = sprite;
		int colUp = col - 1;
		int colDown = col + 1;
		int rowLeft = row - 1;
		int rowRight = row + 1;
		// up one unit test all direction
		if ((colUp) >= 0) {
			mHashMap.put(getKey(row, col), mHashMap.get(getKey(row, colUp)));
			mHashMap.put(getKey(row, colUp), temp);
			int x = 0;
			for (int i = 1; i <= 2; i++) {
				if (colUp - i >= 0
						&& mHashMap.get(getKey(row, colUp)).getStyle() == mHashMap
								.get(getKey(row, colUp - i)).getStyle()) {
					x++;
				}
			}

			if (x >= 2) {
				mHashMap.put(getKey(row, colUp), mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (colUp + i < CELLS_HORIZONTAL
						&& mHashMap.get(getKey(row, colUp)).getStyle() == mHashMap
								.get(getKey(row, colUp + i)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(row, colUp), mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (row - i >= 0
						&& mHashMap.get(getKey(row, colUp)).getStyle() == mHashMap
								.get(getKey(row - i, colUp)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(row, colUp), mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (row + i < CELLS_VERTICAL
						&& mHashMap.get(getKey(row, colUp)).getStyle() == mHashMap
								.get(getKey(row + i, colUp)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(row, colUp), mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			mHashMap.put(getKey(row, colUp), mHashMap.get(getKey(row, col)));
			mHashMap.put(getKey(row, col), temp);
		}
		// down one unit test all direction
		if ((colDown) < CELLS_HORIZONTAL) {
			mHashMap.put(getKey(row, col), mHashMap.get(getKey(row, colDown)));
			mHashMap.put(getKey(row, colDown), temp);
			int x = 0;
			for (int i = 1; i <= 2; i++) {
				if (colDown - i >= 0
						&& mHashMap.get(getKey(row, colDown)).getStyle() == mHashMap
								.get(getKey(row, colDown - i)).getStyle()) {
					x++;
				}
			}

			if (x >= 2) {
				mHashMap.put(getKey(row, colDown),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (colDown + i < CELLS_HORIZONTAL
						&& mHashMap.get(getKey(row, colDown)).getStyle() == mHashMap
								.get(getKey(row, colDown + i)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(row, colDown),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (row - i >= 0
						&& mHashMap.get(getKey(row, colDown)).getStyle() == mHashMap
								.get(getKey(row - i, colDown)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(row, colDown),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (row + i < CELLS_VERTICAL
						&& mHashMap.get(getKey(row, colDown)).getStyle() == mHashMap
								.get(getKey(row + i, colDown)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(row, colDown),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			mHashMap.put(getKey(row, colDown), mHashMap.get(getKey(row, col)));
			mHashMap.put(getKey(row, col), temp);
		}
		// left one unit test all direction
		if ((rowLeft) >= 0) {
			mHashMap.put(getKey(row, col), mHashMap.get(getKey(rowLeft, col)));
			mHashMap.put(getKey(rowLeft, col), temp);
			int x = 0;
			for (int i = 1; i <= 2; i++) {
				if (col - i >= 0
						&& mHashMap.get(getKey(rowLeft, col)).getStyle() == mHashMap
								.get(getKey(rowLeft, col - i)).getStyle()) {
					x++;
				}
			}

			if (x >= 2) {
				mHashMap.put(getKey(rowLeft, col),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (col + i < CELLS_HORIZONTAL
						&& mHashMap.get(getKey(rowLeft, col)).getStyle() == mHashMap
								.get(getKey(rowLeft, col + i)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(rowLeft, col),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (rowLeft - i >= 0
						&& mHashMap.get(getKey(rowLeft, col)).getStyle() == mHashMap
								.get(getKey(rowLeft - i, col)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(rowLeft, col),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (rowLeft + i < CELLS_VERTICAL
						&& mHashMap.get(getKey(rowLeft, col)).getStyle() == mHashMap
								.get(getKey(rowLeft + i, col)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(rowLeft, col),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			mHashMap.put(getKey(rowLeft, col), mHashMap.get(getKey(row, col)));
			mHashMap.put(getKey(row, col), temp);
		}
		// right one unit test all direction
		if ((rowRight) < CELLS_VERTICAL) {
			mHashMap.put(getKey(row, col), mHashMap.get(getKey(rowRight, col)));
			mHashMap.put(getKey(rowRight, col), temp);
			int x = 0;
			for (int i = 1; i <= 2; i++) {
				if (col - i >= 0
						&& mHashMap.get(getKey(rowRight, col)).getStyle() == mHashMap
								.get(getKey(rowRight, col - i)).getStyle()) {
					x++;
				}
			}

			if (x >= 2) {
				mHashMap.put(getKey(rowRight, col),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (col + i < CELLS_HORIZONTAL
						&& mHashMap.get(getKey(rowRight, col)).getStyle() == mHashMap
								.get(getKey(rowRight, col + i)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(rowRight, col),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (rowRight - i >= 0
						&& mHashMap.get(getKey(rowRight, col)).getStyle() == mHashMap
								.get(getKey(rowRight - i, col)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(rowRight, col),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			x = 0;
			for (int i = 1; i <= 2; i++) {
				if (rowRight + i < CELLS_VERTICAL
						&& mHashMap.get(getKey(rowRight, col)).getStyle() == mHashMap
								.get(getKey(rowRight + i, col)).getStyle()) {
					x++;
				}
			}
			if (x >= 2) {
				mHashMap.put(getKey(rowRight, col),
						mHashMap.get(getKey(row, col)));
				mHashMap.put(getKey(row, col), temp);
				return true;
			}
			mHashMap.put(getKey(rowRight, col), mHashMap.get(getKey(row, col)));
			mHashMap.put(getKey(row, col), temp);
		}
		return false;
	}

	/**
	 * 水平消去
	 */
	private int removeHorizontal() {
		int k = 0;
		int m = 0;
		int r = 0;
		for (int i = 0; i < CELLS_VERTICAL; i++) {
			for (int j = 0; j < CELLS_HORIZONTAL - 2; j++) {
				r = 0;
				if (mHashMap.get(getKey(j, i)).getState() == STATE_NORMAL
						|| mHashMap.get(getKey(i, j)).getState() == STATE_SCALEINT) {
					if (mHashMap.get(getKey(j, i)).getState() == STATE_NORMAL)
						r = 1;
					for (k = 1; j + k < CELLS_HORIZONTAL
							&& mHashMap.get(getKey(j, i)).getStyle() == mHashMap
									.get(getKey(j + k, i)).getStyle(); k++)
						if (STATE_NORMAL == mHashMap.get(getKey(j + k, i))
								.getState())
							++r;
					if (k >= 3 && r > 0) {
						m = 1;
						if (mHashMap.get(getKey(j, i)).getStyle() == mark1
								|| mHashMap.get(getKey(j, i)).getStyle() == mark2) {
							this.addScore(r * 2);
						} else
							this.addScore(r);
						for (int n = 0; n < k; n++) {
							mHashMap.get(getKey(j++, i)).setState(
									STATE_SCALEINT);
						}
					}
				}
			}
		}
		return m;
	}

	/**
	 * 垂直消去
	 */
	private int removeVrtical() {
		int m = 0;
		int k = 0;
		int r = 0;
		for (int i = 0; i < CELLS_HORIZONTAL; i++) {
			for (int j = 0; j < CELLS_VERTICAL - 2; j++) {
				r = 0;
				if (mHashMap.get(getKey(i, j)).getState() == STATE_NORMAL
						|| mHashMap.get(getKey(i, j)).getState() == STATE_SCALEINT) {
					if (mHashMap.get(getKey(j, i)).getState() == STATE_NORMAL)
						r = 1;
					for (k = 1; j + k < CELLS_VERTICAL
							&& mHashMap.get(getKey(i, j)).getStyle() == mHashMap
									.get(getKey(i, j + k)).getStyle(); k++) {
						if (STATE_NORMAL == mHashMap.get(getKey(j + k, i))
								.getState())
							++r;
					}
					if (k >= 3 && r > 0) {
						m = 1;
						if (mHashMap.get(getKey(i, j)).getStyle() == mark1
								|| mHashMap.get(getKey(i, j)).getStyle() == mark2)
							this.addScore(r * 2);
						else
							this.addScore(r);
						for (int n = 0; n < k; n++) {
							mHashMap.get(getKey(i, j++)).setState(
									STATE_SCALEINT);
						}
					}
				}
			}
		}
		return m;
	}

	/**
	 * 扫描完毕之后，根据有没有消去的来决定是否跳变状态
	 */
	private void changeState() {
		int fallCount = 0;
		for (int i = 0; i < CELLS_HORIZONTAL; i++) {
			for (int j = 0; j < CELLS_VERTICAL; j++) {
				if (mHashMap.get(getKey(j, i)).getState() == STATE_SCALEINT) {
					fallCount++;
				}
			}
		}
		if (fallCount > 0 && STATE == CHECK) {
			STATE = FALL;
		} else {
			mLongestChainTemp = 0;
			scoreratio = (float) ((mLongestChainTemp * 0.5 + 1) * (mChapter * 0.2 + 0.8));// update
																							// scoreratio
			this.mScoreRatio.setText(String.format("%.1f倍", scoreratio));
			checkMapDead(); // 死局检测
		}
	}

	/**
	 * 交换后是否需要消去
	 * 
	 * @return ture/false(有/无消去的)
	 */
	private boolean isSwapFall() {
		int count = 0;
		// 当前钻石的行检测
		if (checkHorizontal(mHashMap.get(getKey(mCurRow, mCurCol))).size() >= 3) {
			count += 1;
		}
		// 上一个钻石的行检测
		if (checkHorizontal(mHashMap.get(getKey(mLastRow, mLastCol))).size() >= 3) {
			count += 1;
		}
		// 当前钻石的列检测
		if (checkVertical(mHashMap.get(getKey(mCurRow, mCurCol))).size() >= 3) {
			count += 1;
		}
		// 上一个钻石的列检测
		if (checkVertical(mHashMap.get(getKey(mLastRow, mLastCol))).size() >= 3) {
			count += 1;
		}

		if (count == 0) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 检测水平方向
	 * 
	 * @param jewel
	 * @return int 水平方向能消去到队列的个数
	 */
	private ArrayList<JewelSprite> checkHorizontal(final JewelSprite jewel) {
		ArrayList<JewelSprite> deadArrayList = new ArrayList<JewelSprite>();
		if (jewel != null) {
			int curRow = jewel.getRow();
			final int curCol = jewel.getCol();
			final int curStyle = jewel.getStyle();
			// 向左检测
			while ((curRow - 1) >= 0) {
				if (mHashMap.get(getKey(curRow - 1, curCol)) != null) {
					if (curStyle == mHashMap.get(getKey(curRow - 1, curCol))
							.getStyle()) {
						deadArrayList.add(mHashMap.get(getKey(curRow - 1,
								curCol)));
					} else {// 出现不连续的，跳过去
						curRow = 0;
					}
				}
				curRow -= 1;
			}
			curRow = jewel.getRow();// 回来原位重新开始
			deadArrayList.add(mHashMap.get(getKey(curRow, curCol)));
			// 向右检测
			while ((curRow + 1) < CELLS_VERTICAL) {
				if (mHashMap.get(getKey(curRow + 1, curCol)) != null) {
					if (curStyle == mHashMap.get(getKey(curRow + 1, curCol))
							.getStyle()) {
						deadArrayList.add(mHashMap.get(getKey(curRow + 1,
								curCol)));
					} else {// 出现不连续的，跳过去
						curRow = CELLS_VERTICAL;
					}
				}
				curRow += 1;
			}
		}
		return deadArrayList;
	}

	/**
	 * 检测垂直方向
	 * 
	 * @param jewel
	 * @return int 垂直方向能消去到队列的个数
	 */
	private ArrayList<JewelSprite> checkVertical(final JewelSprite jewel) {
		ArrayList<JewelSprite> deadArrayList = new ArrayList<JewelSprite>();
		if (jewel != null) {
			ArrayList<JewelSprite> temp = new ArrayList<JewelSprite>();
			final int curRow = jewel.getRow();
			int curCol = jewel.getCol();
			final int curStyle = jewel.getStyle();
			// 向上检测
			while ((curCol - 1) >= 0) {
				if (mHashMap.get(getKey(curRow, curCol - 1)) != null) {
					if (curStyle == mHashMap.get(getKey(curRow, curCol - 1))
							.getStyle()) {
						temp.add(mHashMap.get(getKey(curRow, curCol - 1)));
					} else {// 出现不连续的，跳过去，检查下侧
						curCol = 0;
					}
				}
				curCol -= 1;
			}
			if (temp.size() > 0) {
				for (int p = temp.size() - 1; p >= 0; p--) {
					deadArrayList.add(temp.get(p));
				}
			}
			curCol = jewel.getCol(); // 回来原位重新开始
			deadArrayList.add(mHashMap.get(getKey(curRow, curCol)));
			while ((curCol + 1) < CELLS_HORIZONTAL) {// 向下检测
				if (mHashMap.get(getKey(curRow, curCol + 1)) != null) {
					if (curStyle == mHashMap.get(getKey(curRow, curCol + 1))
							.getStyle()) {
						deadArrayList.add(mHashMap.get(getKey(curRow,
								curCol + 1)));
					} else {// 出现不连续的，跳过去
						curCol = CELLS_HORIZONTAL;
					}
				}
				curCol += 1;
			}
		}
		return deadArrayList;
	}

	/**
	 * 相邻两颗钻石在HashMap里交换位置
	 */
	private void swapInHashMap() {
		// HashMap里互换
		JewelSprite temp = mHashMap.get(getKey(mLastRow, mLastCol));
		mHashMap.remove(getKey(mLastRow, mLastCol));
		mHashMap.put(getKey(mLastRow, mLastCol),
				mHashMap.get(getKey(mCurRow, mCurCol)));
		mHashMap.remove(getKey(mCurRow, mCurCol));
		mHashMap.put(getKey(mCurRow, mCurCol), temp);
	}

	/**
	 * 随机获取一个钻石精灵
	 */
	public JewelSprite getRandomJewel(final int row, final int col) {
		int style = MathUtils.random(0, 7);
		Log.w("lhl", String.valueOf(row) + ":" + String.valueOf(col) + ":"
				+ String.valueOf(style));
		JewelSprite jewelSprite = new JewelSprite(row, col,
				mJewelTextureRegion[style]);
		jewelSprite.setStyle(style);
		return jewelSprite;
	}

	/**
	 * 是否是相邻两颗钻石
	 * 
	 * @return true 相邻
	 * @return false 不相邻
	 */
	private boolean isNext() {
		if ((Math.abs(this.mCurRow - this.mLastRow) == 1 && this.mCurCol == this.mLastCol)// 左右相邻
				|| (Math.abs(this.mCurCol - this.mLastCol) == 1 && this.mCurRow == this.mLastRow)) {// 上下相邻
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 行/列转换成HashMap中到key
	 * 
	 * @return HashMap的key
	 */
	private String getKey(final int row, final int col) {
		return String.valueOf(row) + String.valueOf(col);
	}

	/**
	 * 增长游戏关卡进度
	 */
	private void addBonus() {
		Log.d("bonus", String.valueOf(this.mBonus.getWidth()));
		// 音效
		if (this.mLongestChainTemp == 0)
			this.mRemoveSound.play();
		else if (this.mLongestChainTemp == 1)
			this.mRemoveSound1.play();
		else if (this.mLongestChainTemp == 2)
			this.mRemoveSound2.play();
		else
			this.mRemoveSound3.play();
		// 增加时间

		this.gametime += 1;
		if (gametime > 60)
			gametime = 60;
		// mBonus.setWidth((float) (480)/60*gametime);
		mBonus.getTextureRegion().setTexturePosition(
				-480 / 60 * (60 - gametime), 0);
		mBonus.setPosition(125 - 480 / 60 * (60 - gametime), 210);
		bonusdot.setPosition(107 + (480) / 60 * gametime, 203);
		// 过关
		if (this.mScore >= 1000 && mChapter < 2) {

			this.mChapter = 2;
			this.startNewChapter();
		}
		if (this.mScore >= 2500 && mChapter < 3) {
			this.mChapter = 3;
			this.startNewChapter();
		}
		if (this.mScore >= 4500 && mChapter < 4) {
			this.mChapter = 4;
			this.startNewChapter();
		}
		if (this.mScore >= 7000 && mChapter < 5) {
			this.mChapter = 5;
			this.startNewChapter();
		}
		if (this.mScore >= 10000 && mChapter < 6) {
			this.mChapter = 6;
			this.startNewChapter();
		}
		// else {
		// this.mBonus.setWidth(this.mBonus.getWidth() + mChapterStep);
		// }
		// 更新连击
		this.updateLongestChain();
	}

	/**
	 * 开始新一关
	 */
	private void startNewChapter() {
		// this.mChapterText.setText(String.valueOf(this.mChapter));

		// 新一关的开始
		if (this.mGameModel.equals("timed")) {
			this.gametime = 60;
		}
		// else {
		// this.mBonus.setWidth(0);
		// }
		// if(this.mGameModel.equals("infinite")){//无限模式(每过一关需要的步数增多)
		// this.mChapterStep -= 0.5;
		// }
		// this.mChapterText.setText(String.valueOf(this.mChapter));
		// 新关开始的动画(换背景、最下面一行全部消去)
		// this.changeChapter();

	}

	/**
	 * 更新最长连接
	 */
	private void updateLongestChain() {
		this.mLongestChainTemp++;
		/*
		 * if(mLongestChainTemp > mLongestChain){ mLongestChain =
		 * mLongestChainTemp;
		 * this.mLongestChainText.setText(String.valueOf(mLongestChain)); }
		 */
	}

	/**
	 * 随机获取一个与原来不一样的背景
	 * 
	 * @return
	 */
	/*
	 * private String getRandomBG(){ String bg = ""; int temp =
	 * MathUtils.random(1, 4); while(temp == mCurBGNum){ temp =
	 * MathUtils.random(1, 4); } mCurBGNum = temp; bg = "bground" +
	 * String.valueOf(1) + ".png"; return bg; }
	 */
	/**
	 * 增长分数
	 * 
	 * @param fallCount
	 */
	private void addScore(int fallCount) {
		if (checkPoint()) {
			scoreratio = (float) ((mLongestChainTemp * 0.5 + 1) * (mChapter * 0.2 + 0.8));// update
			// scoreratio
			this.mScoreRatio.setText(String.format("%.1f倍", scoreratio));
			this.mScore += fallCount * 10 * scoreratio;
			StringBuffer sb = new StringBuffer(mScore);
			while (16 - sb.length() != 0) {
				sb.append("\n");
			}
			this.oldScore = AESUtil.aesEncrypt(sb.toString());
			this.mScoreText.setText(String.format("%07d", this.mScore));
		} else {
			finish();
		}

	}

	/**
	 * 游戏结束提示
	 */

	private void onGameOver() {

		mask.setVisible(true);
		if (isLogin) {
			Dialog dialog = new AlertDialog.Builder(this)
					.setMessage("游戏结束,你当前游戏获得积分：" + this.mScore)
					.setCancelable(false)
					.setPositiveButton("提交积分",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									SUBMITSCORE = 1;
									intentScore = mScore;
									Jewels.this.finish();
								}
							})
					.setNeutralButton("去兑换",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									isIntentToPointShop = true;
									SUBMITANDINTENT = 1;
									intentScore = mScore;
									Jewels.this.finish();

								}
							})
					.setNegativeButton("退出游戏",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									Jewels.this.finish();
								}
							}).create();

			dialog.show();
		} else {
			gamePauseDailog();
		}

	}

	/**
	 * 显示短时间消息提示
	 * 
	 * @param msg
	 */
	private void showLongMessage(String msg) {
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
	}

	/**
	 * 暂停
	 */
	private void onGamePause() {
		mask.setVisible(true);
		gamePauseDailog();

	}

	private void gamePauseDailog() {
		Dialog dialog = new AlertDialog.Builder(this)
				.setMessage("你游戏获得积分：" + this.mScore)
				.setCancelable(false)
				.setPositiveButton("回到游戏",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								// unhideboard();
								mask.setVisible(false);
								if (mIsMusicOn)
									mStartingSound.resume();
								mGameRunning = true;
							}
						})
				.setNeutralButton("新游戏", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						STATE = RESET;
						mask.setVisible(false);
						gametime = 60;
						mGameRunning = true;
					}
				})
				.setNegativeButton("退出游戏",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								Jewels.this.finish();
							}
						}).create();
		dialog.show();
	}
}
